<template>
  <el-form>
    <el-checkbox
      :indeterminate="isIndeterminate"
      v-model="checkAll"
      @change="handleCheckAllChange"
      >全选</el-checkbox
    >
    <div style="margin: 15px 0"></div>
    <el-checkbox-group
      v-model="checkedTypes"
      @change="handleCheckedCitiesChange"
    >
      <el-checkbox
        v-for="(type, index) in types"
        :label="type.id"
        :key="type.id + index"
        :disabled="type.disable"
        >{{ type.value }}</el-checkbox
      >
    </el-checkbox-group>
  </el-form>
</template>

<script>
export default {
  name: "CustomSelect",
  data() {
    return {
      checkAll: false,
      checkedTypes: [],
      types: [],
      isIndeterminate: true,
    };
  },
  computed: {
    len() {
      return this.types.filter((val) => !val.disable).length;
    },
  },
  methods: {
    handleCheckAllChange(val) {
      this.checkedTypes = val
        ? this.types.filter((val) => !val.disable).map((val) => val.id)
        : [];
      console.log(this.checkedTypes);
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.len;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.len;
    },
  },
  mounted() {
    const _this = this;
    this.$axios({
      method: "GET",
      url: `https://anyshare.izhen.top/api/metadata/v1/templates`,
      headers: {
        authorization: "Bearer " + this.$token,
      },
    })
      .then((res) => {
        const type_list = [];
        for (let i = 0; i < res.data.entries.length; i++) {
          type_list.push({
            id: res.data.entries[i]["key"],
            value: res.data.entries[i]["display_name"],
            disable: false,
          });
        }

        console.log("type_list");
        console.log(type_list);

        _this.types = type_list;
      })
      .catch((error) => {
        console.log(error);
      });
  },
};
</script>
